package com.wh.wisdomsite.xbox.us.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wh.wisdomsite.xbox.us.dao.CompanyMapper;
import com.wh.wisdomsite.xbox.us.dao.OfficeMapper;
import com.wh.wisdomsite.xbox.us.entity.Company;
import com.wh.wisdomsite.xbox.us.entity.Office;
import com.wh.wisdomsite.xbox.us.service.ICompanyService;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 公司serviceImpl
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.us.service.impl
 * @date 2018年08月06日 22:41
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Service("companyService")
@Transactional(rollbackFor = {Exception.class,RuntimeException.class})
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {
    private static final Log logger = LogFactory.getLog(CompanyServiceImpl.class);

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private OfficeMapper officeMapper;

    // 公司表初始企业编码
    private static final String INITCOMPANYCODE = "520";

    /**
     * 带条件查询的情况下获取数据的层级
     * @return
     */
    @Override
    public List<Company> getMenuListForSerch(List<Company> parentList){
        List<Company> treeCompanyList = new ArrayList<Company>();
        int num = parentList.size();
        for(int i =0;i<num;i++){
            Map map = new HashMap();
            List<Integer> companyIds = new ArrayList<Integer>();
            Map mapResult = getNodeFloorTree(parentList.get(i),parentList,companyIds,map);
            Company company = (Company) mapResult.get("company");
            List<Integer> companyIdResult = (List<Integer>) mapResult.get("compnayIds");
            treeCompanyList.add(company);
            // 先从集合中移除当前对象
            parentList.remove(i);
            i--;
            num--;
            // 再从集合中移除当前对象的子集
            int num1 = parentList.size();
            for(int j=0;j<num1;j++){
                boolean equalFlag = false;
                for(Integer companyId : companyIdResult){
                    if(parentList.get(j).getCompanyId().equals(companyId)){
                        parentList.remove(j);
                        equalFlag = true;
                        num--;
                        num1--;
                    }
                }
                if(equalFlag){
                    j--;
                }
            }
        }
        return treeCompanyList;
    }

    /**
     * 获取当前节点的树形结构，同时返回此节点树的主键，用作父方法从集合中去掉对应的对象
     * @param company
     * @param companyList
     * @return
     */
    Map getNodeFloorTree(Company company,List<Company> companyList,List<Integer> compnayIds,Map map){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Integer companyIdPr = company.getCompanyId();
        if(null != companyIdPr){
            company.setRegisterDateFormat(company.getRegisterDate() == null?"":sdf.format(company.getRegisterDate()));
            List<Company> companyCh = new ArrayList<Company>();
            for(Company company1 : companyList){
                Integer companyIdCh = company1.getParentId();
                if(companyIdPr == companyIdCh){
                    company1.setRegisterDateFormat(company1.getRegisterDate() == null?"":sdf.format(company1.getRegisterDate()));
                    companyCh.add(company1);
                    compnayIds.add(company1.getCompanyId());
                    getNodeFloorTree(company1,companyList,compnayIds,map);
                }
            }
            company.setChildren(companyCh);
            map.put("company",company);
            map.put("compnayIds",compnayIds);
        }
        return map;
    }


    /**
     * 根据传入的父级节点LIST,以及要遍历的companyList，去构建树形结构
     * @param parentCompanyList
     * @param companyList
     * @return
     */
    List<Company> loadChildren(List<Company> parentCompanyList,List<Company> companyList){
        for (Company company : parentCompanyList){
            List<Company> childrenCompanyList = new ArrayList<Company>();
            for(Company companyCh : companyList){
                if(companyCh.getParentId() == company.getCompanyId()){
                    childrenCompanyList.add(companyCh);
                }
            }
            company.setChildren(childrenCompanyList);
            // 迭代添加子菜单
            loadChildren(childrenCompanyList, companyList);
        }
        return parentCompanyList;
    }

    /**
     * 获取树形公司
     * @return
     */
    @Override
    public JSONArray toTreeCompany(List<Company> allCompanyList,Boolean isAdmin) throws Exception{
        JSONArray jsonArray = new JSONArray();
        // 先装载根节点
        for(Company company : allCompanyList){
            if(isAdmin){
                if(0 == company.getParentId()){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id",company.getCompanyId());
                    jsonObject.put("text",company.getName());
                    JSONObject attributeObj = new JSONObject();
                    Integer parentId = company.getParentId();
                    attributeObj.put("parentId",parentId);
                    // 在树里添加自定义对象
                    jsonObject.put("attributes",attributeObj);
                    jsonArray.put(jsonObject);
                }
            }else{
                // 普通用户只用添加根节点即可
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id",company.getCompanyId());
                jsonObject.put("text",company.getName());
                JSONObject attributeObj = new JSONObject();
                Integer parentId = company.getParentId();
                attributeObj.put("parentId",parentId);
                // 在树里添加自定义对象
                jsonObject.put("attributes",attributeObj);
                jsonArray.put(jsonObject);
                break;
            }
        }
        // 传入根节点,装载其子节点
        jsonArray = loadTreeChildren(jsonArray, allCompanyList);
        return jsonArray;
    }

    JSONArray loadTreeChildren(JSONArray parentJsonArray,List<Company> companyList) throws Exception{
        for (int i=0;i<parentJsonArray.length();i++){
            JSONObject obj = parentJsonArray.getJSONObject(i);
            Integer companyId = (Integer)obj.get("id");
            JSONArray childrenCompanyArray = new JSONArray();
            for(Company companyCh : companyList){
                if(companyCh.getParentId() == companyId){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id",companyCh.getCompanyId());
                    jsonObject.put("text",companyCh.getName());
                    JSONObject attributeObj = new JSONObject();
                    Integer parentId = companyCh.getParentId();
                    attributeObj.put("parentId",parentId);
                    // 在树里添加自定义对象
                    jsonObject.put("attributes",attributeObj);
                    childrenCompanyArray.put(jsonObject);
                }
            }
            obj.put("children",childrenCompanyArray);
            // 迭代添加子公司
            loadTreeChildren(childrenCompanyArray, companyList);
        }
        return parentJsonArray;
    }

    @Override
    public String getCompCode(List<Company> companyList, Integer parentId) {
        String compCodeResult = null;
        // 存在父级公司，构造子集编码；不存在则构建父级编码
        if(null != parentId && parentId > 0){
            EntityWrapper<Company> ewCompanyCh = new EntityWrapper<Company>();
            ewCompanyCh.eq("parentId",parentId);
            ewCompanyCh.eq("dataState","1");
            List<Company> companyListCh = companyMapper.selectList(ewCompanyCh);
            // 是否存在子集，构造不同的编码
            if(null != companyListCh && companyListCh.size() > 0){
                //寻找最大编码,并加一
                compCodeResult = getMaxCode(companyListCh);
            }else{
                Company company1 = companyMapper.selectById(parentId);
                String compCode = company1.getCompCode();
                compCodeResult =  compCode+"000";
            }
        }else{
            // 寻找最大编码,并加一
            compCodeResult = getMaxCode(companyList);
        }
        return compCodeResult;
    }

    /**
     * 构造最大编码
     * @param companyList
     * @return
     */
    String getMaxCode(List<Company> companyList){
        String maxCode = "0";
        for(Company companySerch : companyList){
            String compCode1 = companySerch.getCompCode();
            int compareResult = compCode1.compareTo(maxCode);
            if(compareResult > 0){
                maxCode = compCode1;
            }
        }
        // 获取编码最后三位数
        String maxCode1 = maxCode.substring(maxCode.length() - 3,maxCode.length());
        // 需要在获取的三位数前加上"1",避免字符转换为数字时变为"0"
        String structCode = "1"+maxCode1;
        // 给编码加一
        String maxCode2 = String.valueOf(Integer.valueOf(structCode)+1);
        // 将构造的四位编码去掉首位，变为需要的三位编码
        String structCode1 = maxCode2.substring(1,maxCode2.length());
        // 获取最大编码除去最后三位
        String maxCode3 = maxCode.substring(0,maxCode.length() - 3);
        // 将构造的编码组合，得到最终编码
        String maxCode4 = maxCode3 + structCode1;
        return maxCode4;
    }


    @Override
    public Map<String, Object> getMapById(Serializable id) {
        return companyMapper.getMapById(id);
    }

    @Override
    public void saveCompany(Company company,String compCodeArg) throws Exception{
        EntityWrapper<Company> ewCompany = new EntityWrapper<Company>();
        ewCompany.eq("parentId","0");
        ewCompany.eq("dataState","1");
        List<Company> companyList = companyMapper.selectList(ewCompany);
        // 表中数据是否为空，为空要加入初始企业编码
        if(null != companyList && companyList.size() > 0){
            // 如果主键不为空，则更新
            if(null != company.getCompanyId()){
                // 获取原公司数据
                Company companyInitially = companyMapper.selectById(company.getCompanyId());
                Integer parentId = company.getParentId();
                String compCode = companyInitially.getCompCode();
                // parentId为空表示页面没有选中，则赋值为0(根级）
                if(parentId == null){
                    parentId = 0;
                }
                // 如果父级id变化，当前对象编码需要改变
                if(null != parentId && companyInitially.getParentId() != parentId){
                    compCode = getCompCode(companyList,parentId);
                }
                company.setCompCode(compCode);
                company.setParentId(parentId);
                company.setUpdateDate(new Date());
                companyMapper.updateById(company);
                // 如果父级id变化，更新当前对象的子集编码
                if(companyInitially.getParentId() != parentId){
                    updateChildCode(company,compCodeArg);
                }
            }else{
                Integer parentId = company.getParentId();
                String compCode = getCompCode(companyList,parentId);
                //parentId为空表示页面没有选中，则赋值为0(根级）
                if(parentId == null){
                    parentId = 0;
                }
                company.setCompCode(compCode);
                company.setParentId(parentId);
                company.setCreateDate(new Date());
                companyMapper.insert(company);
            }
        }else{
            company.setCompCode(INITCOMPANYCODE);
            company.setParentId(0);
            companyMapper.insert(company);
        }
    }

    /**
     *  更新节点对象的子集编码
     */
    void updateChildCode(Company company,String compCodeArg){
        EntityWrapper<Company> ewCompany = new EntityWrapper<Company>();
        ewCompany.setEntity(new Company());
        if(StringUtils.isNotEmpty(compCodeArg)){
            ewCompany.like("compCode",compCodeArg);
        }
        ewCompany.eq("dataState","1");
        ewCompany.orderBy("compCode",true);
        // 获取条件公司数据
        List<Company> allCompanyList = companyMapper.selectList(ewCompany);
        List<Company> singalCompany = new ArrayList<Company>();
        singalCompany.add(company);
        // 获取当前节点及以下所有子节点
        List<Company> treeCompanyList = loadChildren(singalCompany, allCompanyList);
        // 获取子集
        List<Company> getChildrenList = treeCompanyList.get(0).getChildren();
        if(getChildrenList.size() > 0){
            updateChildCode1(company.getCompCode(),getChildrenList);
        }
    }

    /**
     * 更新节点对象的子集编码步骤1
     * @param companyCode
     * @param companyList
     */
    void updateChildCode1(String companyCode,List<Company> companyList){
        for(int i=0;i<companyList.size();i++){
            Integer structCode = 1000;
            // 给初始编码加编号
            String maxCode = String.valueOf(structCode+i);
            // 将构造的四位编码去掉首位，变为需要的三位编码
            String structCode1 = maxCode.substring(1,maxCode.length());
            // 构造当前对象的子集编码
            String structCode2 = companyCode + structCode1;
            Company company = companyList.get(i);
            company.setCompCode(structCode2);
            companyMapper.updateById(company);
            updateOfficeCode(company.getCompanyId(),structCode2);
            List<Company> companyList1 = company.getChildren();
            if(companyList1.size() > 0){
                updateChildCode1(structCode2,companyList1);
            }
        }
    }

    /**
     * 变更公司下的部门编码
     * @param companyId
     */
    void updateOfficeCode(Integer companyId,String companyCode){
        if(null != companyId){
            EntityWrapper<Office> ewOffice = new EntityWrapper<Office>();
            ewOffice.eq("companyId",companyId);
            ewOffice.eq("dataState",1);
            List<Office> officeList = officeMapper.selectList(ewOffice);
            if(officeList.size() > 0){
                for(Office office : officeList){
                    String officeCode = office.getOfficeCode();
                    String[] spCode = officeCode.split("-");
                    String lastCode = spCode[1];
                    String resultCode = companyCode + "-" + lastCode;
                    office.setOfficeCode(resultCode);
                    officeMapper.updateById(office);
                }
            }
        }
    }

    @Override
    public String getChildCompIds(Integer id) {
        String ids = null;
        if(null != id){
            String childs = companyMapper.getChildCompIds(id);
            if(StringUtils.isNotEmpty(childs)){
                ids = childs;
            }
        }
        return ids;
    }

    /**
     * 验证公司名称是否已经存在
     * @param companyName
     * @param oldCompanyName
     * @return
     */
    @Override
    public boolean companyNameIsExists(String companyName, String oldCompanyName) {
        //判断是否有原始值，有原始值则为修改, 且原始值跟新值不相同，才进行查询，否则直接返回false
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(oldCompanyName) && companyName.equals(oldCompanyName)){
            return false;
        }
        //设置条件
        EntityWrapper<Company> ew = new EntityWrapper<>();
        ew.setEntity(new Company());
        ew.eq("name", companyName);
        return companyMapper.selectCount(ew) > 0;
    }

}
